<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const nodes = [
      { id: 3, name: '节点C', parentId: 1 },
      { id: 6, name: '节点F', parentId: 3 },
      { id: 0, name: 'root', parentId: null },
      { id: 1, name: '节点A', parentId: 0 },
      { id: 8, name: '节点H', parentId: 4 },
      { id: 4, name: '节点D', parentId: 1 },
      { id: 2, name: '节点B', parentId: 0 },
      { id: 5, name: '节点E', parentId: 2 },
      { id: 7, name: '节点G', parentId: 2 },
      { id: 9, name: '节点I', parentId: 5 }
    ];
    function arr2tree (nodes) {
      let result = []
      let map = {}
      nodes.forEach(node => {
        map[node.id] = node
      })
      nodes.forEach(item => {
        let parentId = item.parentId
        if (!map[parentId]) {
          result.push(item)
        } else {
          let parent = map[parentId]
          if (!parent.children) {
            parent.children = []
          }
          parent.children.push(item)
        }
      })
      return result
    }
    function tree2arr (tree) {
      let result = []
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].children === undefined) {
          result.push(tree[i])
        } else {
          let obj = {}
          for (let key in tree[i]) {
            if (key !== 'children' && tree[i].hasOwnProperty(key)) {
              obj[key] = tree[i][key]
            }
          }
          result.push(obj)
          result.push(...tree2arr(tree[i].children))
        }
      }
      return result
    }
    let tree = arr2tree(nodes)
    console.log(tree);
    let nodesList = tree2arr(tree)
    console.log(nodesList);
  </script>
</body>

</html>